package admin

import (
	"common/uuid"
	"errors"
	"gorm.io/gorm"
	"net/http"
)

func (server *Server) addBucket(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	var input struct {
		Bucket string    `json:"bucket" validate:"required,max=100"`
		UserId uuid.UUID `json:"user_id" validate:"required"`
	}

	err := bind(r, &input)
	if err != nil {
		server.sendJSONError(w, "failed to unmarshal request",
			err.Error(), http.StatusBadRequest)
		return
	}

	//检查bucket是否存在
	bucket, err := server.db.GetBucketByName(ctx, input.Bucket, input.UserId)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		server.sendJSONError(w, "server error",
			err.Error(), http.StatusInternalServerError)
		return
	}

	if bucket.ID.IsZero() {
		bucket.Bucket = input.Bucket
		bucket.OwnerId = input.UserId
		err = server.db.AddBucket(ctx, bucket)
		if err != nil {
			server.sendJSONError(w, "server error",
				err.Error(), http.StatusInternalServerError)
			return
		}
	}
	server.sendJSONData(w, http.StatusOK, bucket)
}
